<?php


namespace app\app\controller;


use app\common\controller\Homebase;
use EasyWeChat\Factory;
use think\Db;

class UserBase extends Homebase
{
    protected $openid;
    protected $memberInfo;
    protected $memberId;

    protected function initialize()
    {
        parent::initialize();
        $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        if (empty($authorization)) {
            responseJson(-100, '请先登录');
        }
        //todo 使用明文openid 后面加密 解密
        $openid = $authorization;

        $user = Db::name('member')->where('openid', '=', $openid)
            ->field('id,openid,nickname,avatarUrl,mobile,status')->find();
        if (!strpos($user['avatarUrl'], 'ttp')){
            $user['avatarUrl']=config('wechat.url').$user['avatarUrl'];
        }
        if (!$user) {
            responseJson(-100, '登录信息有误');
        }
        if ($user['status']==0) {
            responseJson(-200, '用户已冻结');
        }
        $this->openid = $openid;
        $this->memberInfo = $user;
        $this->memberId = $user['id'];
    }

    public function getAddress()
    {
        $where[] = ['is_default_address', '=', 1];
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $this->memberInfo['id']];
        $data = Db::name('delivery_address')->where($where)->find();
        return $data;
    }

    public function getAddressById($id)
    {
        return Db::name('delivery_address')->find($id);
    }

    //通过商品id返回商品信息
    public function getGoodsById($id)
    {
        return Db::name('goods')->find($id);
    }
    //============================================== 服务站支付
    //微信小程序对接支付 测试
    public function wapay2()
    {
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $userinfo = $this->memberInfo;
        $jssdk = $app->jssdk;
        $result = $app->order->unify([
            'body' => '服务站订货',
            'out_trade_no' => time().range(100000,999999),
            //todo 测试一分钱
            'total_fee' => 1,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => 'o414G0TDgXReHCd5vRnFrQdROmL8',
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //微信小程序对接支付
    public function wapay()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_type = $data['order_type']; //1服务站订单 2用户订单 3用户水票订单 目前走通服务站订单
        $orderdata = Db::name('business_order')
            ->where('order_no', '=', $order_no)
            ->where('pay_status','=',0)
            ->find();
        if(!$orderdata){
            msg(-1, '订单有误', '');
        }
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $userinfo = $this->memberInfo;
        $jssdk = $app->jssdk;
        $result = $app->order->unify([
            'body' => '服务站订货',
            'out_trade_no' => $orderdata['order_no'],
            'total_fee' => $orderdata['cash'] * 100,
            //todo 测试一分钱
 //           'total_fee' => 1,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userinfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $orderdata['order_no'];
            $result['order_id'] = $orderdata['id'];
            $result['type'] = $order_type;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //支付完成后回调
    public function uporder()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_type = $data['order_type'];
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $order_data = Db::name('business_order')
            ->where('order_no', '=', $order_no)
            ->find();
        $res = $app->order->queryByOutTradeNumber($order_data['order_no']);
        if ($res['trade_state'] == "SUCCESS") {
            //服务站支付成功后自己写逻辑 并返回
            $this->BusinessOrderPayed($order_data['id']);
            $order_data = Db::name('business_order')
                ->where('order_no', '=', $order_no)
                ->find();
            msg(0, "支付成功！", $order_data);
        } else {
            msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
        }
    }

    //服务站订单支付完成修改状态
    public function BusinessOrderPayed($order_id)
    {
        Db::startTrans();
        try {
            //通过订单获取服务站id todo 整合订单
            $business_order_info = Db::name('business_order')
                ->find($order_id);
            if ($business_order_info['pay_status'] == 1) {
                msg(-1, '订单已支付', $business_order_info['pay_status']);
            }
            $update_info = array(
                'id' => $order_id,
                'status' => 1, //'0待支付 1待发货 2已完成',
                'pay_status' => 1,//'支付状态 0未支付1已支付',
                'pay_time' => time()
            );
            $update_id = Db::name('business_order')->update($update_info);
            //'支付方式 1余额支付 2直接支付 3混合支付',
            if ($business_order_info['pay_type'] != 2) {
                $finance_insert_data = array(
                    'business_id' => $business_order_info['business_id'],
                    'amount' => $business_order_info['balance'],
                    'type' => 3, //1.推广 2线上销售 3进货 4提现
                    'create_time' => time(),
                    'is_count' => 2//1加 2减
                );
                $business_finance_id = Db::name('business_finance')->insertGetId($finance_insert_data);
                Db::name('business')
                    ->where('id', $business_order_info['business_id'])
                    ->setDec('amount', $business_order_info['balance']);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

}